﻿using System;
using System.Configuration;
using System.Web.UI;
using AutoStopData.BussinessLogic;
using AutoStopData.Model;

namespace AutoStopApp.Core
{
    public static class SessionProvider
    {
        private static readonly int LOG_ACTIVITY_INTERVAL_SECONDS;
        private static UserControl _control;

        static SessionProvider()
        {
            LOG_ACTIVITY_INTERVAL_SECONDS = Int32.Parse(ConfigurationManager.AppSettings["LOG_ACTIVITY_INTERVAL_SECONDS"]);
        }

        public static void Initialize(UserControl control)
        {
            _control = control;
        }

        public static Session CurrentSession
        {
            get
            {
                Session retVal = null;
                if (_control.Session["CurrentSession"] != null)
                {
                    retVal = _control.Session["CurrentSession"] as Session;
                }
                return retVal;
            }
            set
            {
                _control.Session["CurrentSession"] = value;
            }
        }

        public static void LogOut()
        {
            Sessions.UpdateSetLoggedOut(CurrentSession.SessionId);
            _control.Session.Clear();
            _control.Response.Redirect("/");
        }

        public static bool CanLogActivity()
        {
            bool retVal = false;
            var currentSession = CurrentSession;
            if (currentSession != null)
            {
                if (currentSession.LastAccess.AddSeconds(LOG_ACTIVITY_INTERVAL_SECONDS) < DateTime.Now)
                {
                    retVal = true;
                }
            }
            System.Diagnostics.Debug.WriteLine(retVal);
            return retVal;
        }
    }
}